package cn.edu.scau.cmi.codeGenerate.filter;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;

import cn.edu.scau.cmi.codeGenerate.util.CharArrayWrapper;

@WebFilter(filterName="ResponseSecurityFilter", urlPatterns="/*")
public class ResponseSecurityFilter implements Filter {
	public void destroy() {
	}
	public void doFilter(ServletRequest request, ServletResponse response,	FilterChain filterChain) throws IOException, ServletException {
//		把response对象封装为wrapper对象
		CharArrayWrapper charArrayWrapper = new CharArrayWrapper((HttpServletResponse) response);
//		TODO 输出打印一下，看是什么结果
		System.out.println("到达servlet之前的response内容：\n"+charArrayWrapper);

		filterChain.doFilter(request, charArrayWrapper);
		
		boolean isSecurityFreeServletPath=false;
		if(isSecurityFreeServletPath){
			System.out.println(((HttpServletRequest) request).getServletPath()+"该资源不是要生成的代码");
		}
		else{
			System.out.println(((HttpServletRequest) request).getServletPath()+"准备生成代码 ");
			System.out.println("返回到页面t之前的response内容：\n"+charArrayWrapper);
			//过滤掉没有权限的功能后的输出，封装为String类型
//			String httpResponseString = SecurityUtil.fiterNotAuthorizedfunctionFromResponse(req, resp, wrapper);
			//将过滤了的response输出到浏览器页面				
			FileUtils.writeStringToFile(new File("d:/index.jsp"), charArrayWrapper.toString());
			write(response, charArrayWrapper.toString());
		}
	}
	/**
	 *将生成的文件保存
	 * @param response
	 * @param httpResponseString
	 * @throws IOException
	 */
	private void write(ServletResponse response, String httpResponseString)	throws IOException {
		
		// 处理返回结果
		PrintWriter out = response.getWriter();
		out.write(httpResponseString);
		out.flush();
		out.close(); // 输出处理后的结果
	}
	public void init(FilterConfig arg0) throws ServletException {

	}
}